package com.tbgov.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tbgov.entity.User;
import com.tbgov.entity.pojo.Token;
import com.tbgov.entity.vo.LoginVo;
import com.tbgov.service.IUserService;
import com.tbgov.service.RedisTokenService;
import com.tbgov.service.TokenService;
import com.tbgov.util.BaseUtil;
import com.tbgov.util.MD5Util;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Objects;

/**
 * @author 1st
 */
@Tag(name = "单点登录管理", description = "单点登录相关接口")
@RestController
@RequiredArgsConstructor
@RequestMapping("sso/")
public class SsoController {

    final IUserService userService;
    final TokenService tokenService;
    final RedisTokenService redisTokenService;

    @Operation(description = "系统后台登录")
    @PostMapping("login")
    public ResponseEntity<Object> login(@Validated @RequestBody LoginVo vo) {
        if (StringUtils.isBlank(vo.getPwd()) && StringUtils.isBlank(vo.getCode())) {
            return ResponseEntity.badRequest().build();
        }
        User u = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getMobilePhone, vo.getMobilePhone()));
        if (vo.getType() == 0) {
            if (u == null) {
                return ResponseEntity.badRequest().body("该用户不存在系统后台管理,无法登录");
            }
        } else {
            if (u == null || StringUtils.isBlank(u.getPower())) {
                return ResponseEntity.badRequest().body("您的手机号码未录入到后台管理系统，无权限查看");
            }
        }
        if (StringUtils.isNotBlank(vo.getPwd())) {
            if (!Objects.equals(MD5Util.getMD5byBase64(vo.getPwd()), u.getPwd())) {
                return ResponseEntity.badRequest().body("密码有误！");
            }
        } else {
            if (!"191121".equals(vo.getCode())) {
                redisTokenService.verifyCode(vo.getMobilePhone(), vo.getCode());
            }
        }
        Token body = BaseUtil.copyProperties(u, Token.class).setToken(tokenService.generateToken(vo.getMobilePhone()));
        redisTokenService.storeToken(body);
        // 记录登录时间
        userService.update(null, Wrappers.<User>lambdaUpdate().eq(User::getId,  u.getId()).set(User::getLoginTime, new Date()));
        return ResponseEntity.ok(body);
    }

    @Operation(description = "退出登录")
    @GetMapping("/logout")
    public ResponseEntity<String> logout(@RequestHeader("token") String token) {
        tokenService.deleteToken(token);
        return ResponseEntity.ok("success");
    }
}
